/**
 * @author 张雨生
 * @desc 业务字典
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-dict'),
        $query = $view.find('#query'),
        $edit = $view.find('#edit'),
        $delete = $view.find('#delete'),
        $searchForm = $view.find('#dict-table-form'),
        tableIns;

    form.verify(validate);
    form.render();

    initTable();

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'dictTable',
            height: getTableHeight(),
            skin: '',
            cols: [[
                {type: 'numbers',title:'序号', width: 60},
                {field: 'dictCode', title: '字典编码', minWidth: 220},
                {field: 'dictName', title: '字典名称', width: 180},
                {field: 'status', title: '状态', align:'center',toolbar: '#status-bar' , width: 120  },
                {field: 'dictItems', title: '包含项目', minWidth: 220,
                    templet: function(d){
                        let returnText = ""

                        $.each(d.dictItems,function (index,item){
                            if("1" == item.itemStatus){
                                returnText += `<button class="layui-btn layui-btn-xs layui-btn-success" >${item.itemName}</button>`
                            }else{
                                returnText += `<button class="layui-btn layui-btn-xs layui-btn-disabled" disabled>${item.itemName}</button>`
                            }
                        })
                        if(commonJS.isEmpty(returnText)){
                            returnText = "--"
                        }
                        return returnText;
                    }
                },
                {field: 'remark', title: '描述', minWidth: 200},
                {title: '操作', toolbar: '#dict-option',align:'center', width: 160}
            ]],
            toolbar: '#dict-toolbar',
            defaultToolbar: []
        });
        tableIns.reload({url: ctx + 'dict/list', where: getQueryParams(), page: {curr: 1}});
    }

    table.on('sort(dictTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    $query.on('click', function () {
        tableIns.reload({where: getQueryParams(), page: {curr: 1}});
    });

    table.on('toolbar(dictTable)', function (obj) {
        if (obj.event === 'add') {
            febs.modal.open('新增', 'dict/add', {
                btn: ['提交', '取消'],
                btnAlign: 'c',
                id: "dictEdit",
                area: $(window).width() <= 750 ? ['90%', '90%'] : ['60%', '90%'],
                yes: function (index, layero) {
                    // $(layero).find("iframe").contents().find("#dict-edit-form").find('#submit').trigger('click');//获取子页面元素
                    $("#dictEdit").find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                },
            });
        }
    });

    $edit.on('click', function () {
        var checkStatus = table.checkStatus('dictTable');
        if (checkStatus.data.length != 1) {
            febs.alert.warn('请选择一条需要修改的数据！');
        } else {
            var id = checkStatus.data[0].dictId;
            febs.modal.open('修改', 'dict/update/'+id, {
                btn: ['提交', '取消'],
                btnAlign: 'c',
                id: "dictEdit",
                area: $(window).width() <= 750 ? ['90%', '90%'] : ['60%', '90%'],
                yes: function (index, layero) {
                    // $(layero).find("iframe").contents().find("#dict-edit-form").find('#submit').trigger('click');//获取子页面元素
                    $("#dictEdit").find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                }
            });
        }
    });

    $delete.on('click', function () {
        var checkStatus = table.checkStatus('dictTable');
        if (!checkStatus.data.length) {
            febs.alert.warn('没有选择要删除的数据！');
        } else {
            febs.modal.confirm('删除数据', '确定删除所选数据？', function () {
                var ids = [];
                layui.each(checkStatus.data, function (key, item) {
                    ids.push(item.dictId);
                });
                deleteIds(ids.join(','));
            });
        }
    });

    table.on('tool(dictTable)', function (obj) {
        //表格编辑删除事件
        var dictId = obj.data.dictId;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            febs.modal.open('修改字典', 'dict/update/'+dictId, {
                btn: ['提交', '取消'],
                btnAlign: 'c',
                id: "dictEdit",
                area: $(window).width() <= 750 ? ['90%', '90%'] : ['60%', '90%'],
                yes: function (index, layero) {
                    $("#dictEdit").find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                }
            });
        } else if (layEvent === 'del') {
            febs.modal.confirm('删除字典', '确定删除所选字典？', function () {
                febs.modal.confirm('删除数据', '确定删除所选数据？', function () {
                    deleteIds(dictId);
                });
            });

        }
    });

    form.on('switch(dictStatus)', function (obj) {
        //岗位状态控制点击事件
        var checked = obj.elem.checked;
        var status;
        if (checked) {
            status = "1";
        } else {
            status = "0";
        }
        let dictId = $(obj.elem).attr("data-id")


        febs.modal.confirm('更改字典状态', '确认更改字典状态',function (){
            updateDictStatus(dictId,status);
        },function (){
            obj.elem.checked = !checked;
            layer.closeAll();
            form.render('checkbox');
        });

    });

    function getQueryParams() {
        return {
            dictCode: $searchForm.find('input[name="dictCode"]').val()?.trim(),
            dictName: $searchForm.find('input[name="dictName"]').val()?.trim(),
            status: $searchForm.find('select[name="status"]').val(),
            invalidate_ie_cache: new Date()
        };
    }

    function deleteIds(ids) {
        febs.get(ctx + 'dict/delete/' + ids, null, function () {
            febs.alert.success('删除数据成功');
            $query.trigger('click');
        })
    }

    function updateDictStatus(dictId,status) {
        //更新岗位状态
        let model={
            dictId : dictId,
            status : status
        }
        febs.post(ctx + 'dict/updateDictStatus', model, function () {
            febs.alert.success('修改字典状态成功');
            $query.trigger('click');
        })
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        tableIns.reload({height: getTableHeight()});
    });
});